package com.xybc.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBManager {
	private final static String DRIVER="com.mysql.jdbc.Driver";
	private final static String URL="jdbc:mysql://localhost:3306/xybcxm";
	private final static String USER="root";
	private final static String PWD="admin";
	
	public static Connection getConn() {
		try {
			Class.forName(DRIVER);
			return DriverManager.getConnection(URL, USER, PWD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void closeAll(Connection conn,Statement st,ResultSet rs) {
		try {
			if(rs!=null) {
				rs.close();
			}
			if(st!=null) {
				st.close();
			}
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static int executeUpdate(String sql) {
		Connection conn=null;
		Statement st=null;
		try {
			conn=getConn();
			st=conn.createStatement();
			return st.executeUpdate(sql);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}finally {
			closeAll(conn, st, null);
		}		
	}

	public static QueryResult executeQuery(String sql) {
		Connection conn=null;
		Statement st=null;
		ResultSet rs=null;
		try {
			conn=getConn();
			st=conn.createStatement();
			rs=st.executeQuery(sql);
			return new QueryResult(conn, st, rs);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
